<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <template #before>共{{ total }}条记录</template>
        <template #after>
          <el-button
            v-if="checkPermission('import')"
            type="warning"
            @click="$router.push({path:'/import',query:{type:'employee'}})"
          >
            导入</el-button>
          <el-button v-if="checkPermission('export')" type="danger" @click="exportEmployee">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" type="primary" @click="$refs.employeeDialog.open()">新增员工</el-button>
        </template>
      </page-tools>
      <!--  给卡片添加一个加载中的效果 -->
      <el-card v-loading="isLoading">
        <el-table :data="list">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column v-slot="{row}" label="头像" sortable>
            <img :src="row.staffPhoto" alt="" class="user-avatar">
          </el-table-column>
          <el-table-column prop="username" label="姓名" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable :formatter="formatter" />
          <el-table-column prop="departmentName" label="部门" sortable />
          <el-table-column v-slot="{ row }" prop="timeOfEntry" label="入职时间" sortable>
            {{ row.timeOfEntry | formatDate }}
          </el-table-column>
          <el-table-column v-slot="{ row }" label="账户状态" sortable>
            <el-switch
              :value="row.enableState"
              :active-value="1"
              :inactive-value="0"
            />
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="$refs.allocateRole.open(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="size"
          class="employee-pagination"
          @current-change="onPageChange"
        />
      </el-card>
    </div>
    <EmployeeDialog ref="employeeDialog" @reload="loadEmployeeList" />
    <AllocateRole ref="allocateRole" />
  </div>
</template>

<script>
import { getEmployeeList, deleteEmployee } from '@/api/employee'
// 导入枚举
import Enum from '@/api/constant/employees'
import EmployeeDialog from './components/employee-dialog.vue'
import AllocateRole from './component/allocateRole.vue'
export default {
  components: { EmployeeDialog, AllocateRole },
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      isLoading: true
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const { rows, total } = await getEmployeeList({
          page: this.page,
          size: this.size
        })
        this.total = total
        this.list = rows
        // console.log(rows)
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false
      }
    },
    // 分页处点击改变页面
    onPageChange(page) {
      this.page = page
      this.loadEmployeeList()
    },
    async delEmployee(id) {
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      await deleteEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      // 刷新数据
      this.loadEmployeeList()
    },
    // 格式化聘用形式
    formatter(row) {
      // row是这一行的数据
      // row.formOfEmployment是雇佣模式 值是1或者2
      // Arry.find查找元素
      // +将字符串转换成为数字
      const item = Enum.hireType.find(item => +row.formOfEmployment === item.id)
      return item ? item.value : '未知'
    },
    // 导出Excel
    exportEmployee() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取当前页的数据
        const { rows } = await getEmployeeList({
          page: this.page,
          size: this.size
        })
        // 定义一个与之相对应的英文数组  item[key] 就可以得到我们想要的相对应的数据
        const enList = ['mobile', 'username', 'timeOfEntry', 'formOfEmployment', 'correctionTime', 'workNumber', 'departmentName']
        // 使用map遍历原数组并按照需求映射出一个新数组
        const result = rows.map(item => {
          // 定义一个空数组接收
          const arr = []
          // 对英文数组遍历 就可以拿到每一个item[key]中的key
          enList.forEach(key => {
            // 对用工形式进行处理
            if (key === 'formOfEmployment') {
              // 使用枚举 经行比较如果1转变成正式 2转变成非正式 其他的转变成未知
              const k = Enum.hireType.find(i => +item[key] === i.id)
              // 放进去数组中
              arr.push(k ? k.value : '未知')
            } else {
              arr.push(item[key])
            }
          })
          return arr
        })
        excel.export_json_to_excel({
          header: ['手机号', '姓名', '入职时间', '聘用形式', '转正日期', '工号', '部门'], // 表头 必填
          multiHeader: [['手机号', '个人信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          data: result, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }
  }
}
</script>

<style scoped>
.employee-pagination {
  text-align: center;
  margin-top: 16px;
}
.user-avatar{
  width: 100%;
}
</style>
